//
//  timeTableAnother.m
//  ElektroM
//
//  Created by Michael on 12.10.09.
//  Copyright 2009 Artgruppe inc. All rights reserved.
//

#import "timeTableAnother.h"
#import "dataBase.h"
#import "Train.h"
#import "AtomicElementViewController.h"
#import "Constants.h"

@implementation timeTableAnother

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
		_direction=1;
		_bUseFilter=true;		
		_db=nil;
    }
    return self;
}

// for loading data from the first view:
-(void)setTimeInfo:(int)StationId withDirection:(int)dir
{
	_nStationId=StationId;
	_direction=dir;
	
	// now update the data:
	[self updateData];
}

-(void)updateData
{
	// here we would use database for showing up a time table:
    if(_db==nil){
	_db=[dataBase alloc];
	_db.namePrefix=_sDataBaseName;	
	_db.databaseName=[_sDataBaseName stringByAppendingString:@"Railways.sqlite"];	
    }

    // get current time:
    NSString *sCurTime;
    if(_bUseFilter)
    {
	NSDate* CurDate=[NSDate date];
	NSDateFormatter *timeFormatter = [[[NSDateFormatter alloc] init] autorelease];
	[timeFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];
	[timeFormatter setDateStyle:NSDateFormatterNoStyle];	
	[timeFormatter setTimeStyle:NSDateFormatterMediumStyle];	

	sCurTime = [timeFormatter stringFromDate:CurDate];
	//printf("Cur time: %s\n", [sCurTime UTF8String]);
    }
    else
	sCurTime=@"00:00:00";

    // read out data from the database:
    [_db initialization];

    _aiTimes = [_db readTimeTableAsNSArray: self._nStationId withTime:sCurTime withDirection:_direction];
    _aiStartStations = [_db getStartStationsAsNSArray];
    _aiEndStations = [_db getEndStationsAsNSArray];
    _aiiTrainInfo = [_db getTrainInfoAsNSArray];
    _aiTrainIds = [_db getTrainIdsAsNSArray];

    if(_direction)
	[self setTitle:NSLocalizedString(@"ToMoscow", @"Shows time table to Moscow")];			
    else
	[self setTitle:NSLocalizedString(@"FromMoscow", @"Shows time table from Moscow")];	

    if(![strTitle isEqualToString:@""])
    {
	self.navigationItem.prompt = strTitle;
    }	

    [tableView reloadData];	
}

- (IBAction) filterAddRemove
{
	if(_bUseFilter)
	{
		_bUseFilter=false;
		[timeFilter setTitle:NSLocalizedString(@"TimeFilter-", @"")];
		[self updateData];
	}
	else
	{
		_bUseFilter=true;
		[timeFilter setTitle:NSLocalizedString(@"TimeFilter+", @"")];
		[self updateData];
	}	
}

- (void)viewDidLoad {
	[timeFilter setTitle:NSLocalizedString(@"TimeFilter+", @"")];
	[super viewDidLoad]; 
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return [_aiTimes count];
}

- (UITableViewCell *)tableView:(UITableView *)tableViewMy cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *kCellIdentifier = @"cellID";
	
	UITableViewCell *cell = [tableViewMy dequeueReusableCellWithIdentifier:kCellIdentifier];
	if (!cell)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kCellIdentifier] autorelease];
        
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        cell.textLabel.backgroundColor = [UIColor clearColor];
		cell.textLabel.opaque = NO;
		cell.textLabel.textColor = [UIColor blackColor];
		cell.textLabel.highlightedTextColor = [UIColor whiteColor];
		cell.textLabel.font = [UIFont boldSystemFontOfSize:18];
		
		cell.detailTextLabel.backgroundColor = [UIColor clearColor];
		cell.detailTextLabel.opaque = NO;
		cell.detailTextLabel.textColor = [UIColor grayColor];
		cell.detailTextLabel.highlightedTextColor = [UIColor whiteColor];
		cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
    }    

	//cell.textLabel.text = [_aiTimes objectAtIndex: indexPath.row];
	cell.textLabel.text = @"12:00";
	
	int nSched=[[_aiiTrainInfo objectAtIndex: indexPath.row] intValue];
	if(nSched!=0 && nSched!=2 && nSched!=3)
	{
		cell.textLabel.textColor = [UIColor greenColor];		
	}
	else if(nSched==2 || nSched==3)		
	    cell.textLabel.textColor = [UIColor redColor];
	else
	    cell.textLabel.textColor = [UIColor blackColor];
	
	
	if(_direction)
		cell.detailTextLabel.text= [_aiStartStations objectAtIndex: indexPath.row];
	else
		cell.detailTextLabel.text= [_aiEndStations objectAtIndex: indexPath.row];
	
	
	return cell;
}

#pragma mark -
#pragma mark UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{  	
	Train* iTrain=[Train alloc];
	iTrain.sTime = [_aiTimes objectAtIndex: indexPath.row];
	iTrain.startStation = [_aiStartStations objectAtIndex: indexPath.row];
	iTrain.endStation = [_aiEndStations objectAtIndex: indexPath.row];
	iTrain.trainNumber=[_aiTrainIds objectAtIndex: indexPath.row];
	iTrain.nInfo = [[_aiiTrainInfo objectAtIndex: indexPath.row] intValue];
	
	if(detailedViewController!=nil)
	{
		[detailedViewController release];
		detailedViewController=nil;
	}
	
	AtomicElementViewController* targetViewController = [AtomicElementViewController alloc];
	[targetViewController init];	
	targetViewController.iTrain=iTrain;
	targetViewController.dataBaseName=_sDataBaseName;
	[targetViewController loadView];
	detailedViewController=targetViewController;
	
    [self.navigationController pushViewController:detailedViewController animated:YES];
}

- (IBAction) filterAddRemoveAnother
{
	[super filterAddRemove];
}

#pragma mark -
#pragma mark BarReleaseStuff
- (void)viewWillAppear:(BOOL)animated{	
	//[self updateData];
	//printf("View appeared!\n");
	//[tableView removeFromSuperview];
	// kick him off, that bustard!
	if(!tabBarController.tabBar.hidden)
	{
		tabBarController.tabBar.hidden=YES;
	}	
	// that busturd did disturb our parent elements:
	// rearrange them:
	tableView.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight-144);
	
	[toolbar removeFromSuperview];
	toolbar.frame=CGRectMake(0, 436, kScreenWidth, 44);
	[tabBarController.view addSubview:toolbar];
}

- (void)viewWillDisappear:(BOOL)animated{
	//printf("View disappeared!\n");
	
	[toolbar removeFromSuperview];
	[self.view addSubview:toolbar];	
}

-(void) releaseUnneededData
{
	//printf("I'm a brother... I want to dissolve myself either\n");	
	if(_db!=nil){
		_db.namePrefix=nil;
		_db.databaseName=nil;	
	    [_db releaseAllElementsOfTimeTableAsNSArray];
	    [_db release];	 
	    _db=nil;	
	}
}


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	/*
	if(_nRecordsCount!=0)		
	{
		for(int i=0; i<_nRecordsCount; i++)
		{
			[_iTimeTables[i].sTime release];
			[_iTimeTables[i].sTrainId release];
		}		
		free(_iTimeTables);
	}
	 */		
	[self.tableView release];
	self.tableView = nil;
	[self._sDataBaseName release];
	self._sDataBaseName = nil;
	[self.strTitle release];
	self.strTitle = nil;
	[self.timeFilter release];
	self.timeFilter = nil;		
}


- (void)dealloc {
	
    [super dealloc];
}


@end
